package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.exceptionHandler.ServiceException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtils;
import com.sky.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
@Slf4j
public class UserServiceImple implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    private static final String WX_OPEN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public UserVO wxLogin(UserLoginDTO userDTO) {
        HashMap<String, String> map = new HashMap<>();

        map.put("appid", weChatProperties.getAppId());
        map.put("secret", weChatProperties.getAppSecret());
        map.put("js_code", userDTO.getCode());
        map.put("grant_type", "authorization_code");

        // 获取openId
        String resp = HttpClientUtils.DoGet(WX_OPEN_URL, map);
        log.info("获取OpenID =>{}", resp);

        JSONObject jsonObject = JSONObject.parseObject(resp);
        String openid = jsonObject.getString("openid");

        if (openid == null) {
            throw new ServiceException("登录失败");
        }


        UserVO user = userMapper.getByOpenId(openid);

        if (user == null) {
            // 说明是新注册用户
            user = UserVO.builder().openId(openid)
                    .avatar(userDTO.getAvatarUrl())
                    .name(userDTO.getNickName())
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        return user;
    }
}
